import {
  logout4A,
  get4AUser,
  getResourceListByUserCode,
} from "../services/public";
import menuData from "../components/layouts/menuData";

const getMenuListData = (data = []) => {
  return data.reduce((prev, item) => {
    const { title, key, link, children, menuId, pageOperate } = item || {};
    const newItem = { title, key, link, menuId, pageOperate };
    if (children) {
      return [...prev, newItem, ...getMenuListData(children)];
    }
    return [...prev, newItem];
  }, []);
};

const menuList = getMenuListData(menuData);

const initData = {
  resourceList: [], // 资源列表
  username: "",
  menuDataList: menuList, // 扁平化的菜单
  // logout: false,
  openMenuKeys: [],
  selectedMenuKeys: [],
};

export default {
  namespace: "Public",
  state: {
    ...initData,
  },
  effects: {
    *logout4A({ payload }, { call }) {
      /*
      yield put({
        type: "set/logout",
        payload: true,
      });
      */
      yield (window.__LOGINED__ = false);
      const { errCode, data = {} } = yield call(logout4A, payload);
      // yield put({ type: "get/detailData", payload: datas || {} });
      return { errCode, data };
    },
    *get4AUser({ payload }, { call }) {
      const { errCode, datas = {} } = yield call(get4AUser, payload);
      // yield put({ type: "get/detailData", payload: datas || {} });
      if (`${errCode}` === "0" && Object.keys(datas).length > 0) {
        yield (window.__LOGINED__ = true);
      }
      return { errCode, datas };
    },
    *setLoadingend() {
      yield (window.__LOGINED__ = true);
    },
    *getResourceListByUserCode({ payload }, { call, put }) {
      /*
      const extras = [
        "page-FlowHome",
        "page-MyTodo", "page-MyTodo-Detail", "/todo/claim", "/todo/handle",
        "page-MyMessage", "page-MyMessage-Detail",
        "page-TaskCenter", "page-TaskCenter-Detail",
        "page-FlowList",
      ];
      */
      const { datas, errCode, errMsg } = yield call(
        getResourceListByUserCode,
        payload,
      );
      // yield put({ type: "get/resourceList", payload: [...datas,...extras]  || [] });
      yield put({ type: "get/resourceList", payload: datas || [] });
      return { errCode, errMsg, datas };
    },
  },
  reducers: {
    "get/resourceList": (state, { payload }) => ({
      ...state,
      resourceList: payload,
    }),
    /*
    "set/logout": (state, { payload }) =>({
      ...state,
      logout: payload,
    }),
    */
    clearData: () => ({ ...initData }),
    "set/openMenuKeys": (state, { payload }) => ({
      ...state,
      openMenuKeys: payload,
    }),
    "set/selectedMenuKeys": (state, { payload }) => ({
      ...state,
      selectedMenuKeys: payload,
    }),
  },
};
